package com.qilu.pe.ui.fragment;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alipay.sdk.app.PayTask;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.ActivityUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.qilu.pe.R;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Config;
import com.qilu.pe.base.Global;
import com.qilu.pe.base.MyApp;
import com.qilu.pe.base.PayResult;
import com.qilu.pe.dao.bean.Doctor;
import com.qilu.pe.dao.bean.Order;
import com.qilu.pe.dao.bean.OrderDetail;
import com.qilu.pe.dao.bean.RefreshEvent;
import com.qilu.pe.dao.bean.UPayInfo;
import com.qilu.pe.dao.bean.WxPayInfo;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.AlertUtil;
import com.qilu.pe.support.util.Logg;
import com.qilu.pe.support.util.PeUtil;
import com.qilu.pe.ui.activity.MyOrderActivity;
import com.qilu.pe.ui.activity.OrderDetailActivity;
import com.qilu.pe.ui.activity.PaySuccessActivity;
import com.qilu.pe.ui.activity.PlaceOrderActivity;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.BaseFragment;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.SizeUtils;
import com.ruitu.arad.util.ToastUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

// 我的订单fragment
public class MyOrder1Fragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener {

    private RecyclerView rcv_list;// 我的订单列表
    private TextView empty_view;

    private MyOrderListAdapter adapter;
    private List<Order> orderList = new ArrayList<>();
    private String type = "";
    private String orderNum;// 订单号
    IWXAPI msgApi;

    private SmartRefreshLayout vRefresh;
    private int mPage = 1, mPageSize = 15;

    private AppCompatEditText et_name;
    private TextView tv_ok, tv_day;
    private LinearLayout ll_time;// 时间
    private Date mTimeFilter;

    public MyOrder1Fragment() {

    }

    public static MyOrder1Fragment newInstance(String type) {
        MyOrder1Fragment fragment = new MyOrder1Fragment();
        Bundle args = new Bundle();
        args.putString("type", type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getArguments().getString("type");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_my_order1, container, false);
        rcv_list = v.findViewById(R.id.rcv_list);
        empty_view = v.findViewById(R.id.empty_view);

        vRefresh = v.findViewById(R.id.vRefresh);
        View searchBar = LayoutInflater.from(getContext()).inflate(R.layout.layout_search_bar, null, false);
        et_name = searchBar.findViewById(R.id.et_name);
        tv_ok = searchBar.findViewById(R.id.tv_ok);
        tv_day = searchBar.findViewById(R.id.tv_day);
        ll_time = searchBar.findViewById(R.id.ll_time);
        tv_ok.setOnClickListener(this);
        ll_time.setOnClickListener(this);

        adapter = new MyOrderListAdapter(orderList);
        adapter.addHeaderView(searchBar);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        rcv_list.setLayoutManager(manager);
        rcv_list.setAdapter(adapter);

        alert = new AlertDialog.Builder(getActivity(), R.style.Dialog_FS).create();
        alert2 = new AlertDialog.Builder(getActivity(), R.style.Dialog_FS).create();

        msgApi = WXAPIFactory.createWXAPI(getActivity(), null);
        msgApi.registerApp(Config.WX_APP_ID);

        EventBus.getDefault().register(this);

        vRefresh.setOnRefreshListener(this);
        vRefresh.setOnLoadMoreListener(this);
        vRefresh.autoRefresh();

        alert.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                // 未支付返回提示信息：您的订单未支付，请尽快完成支付。
                // 继续支付按钮/确认离开按钮，点击确认离开跳转到我的订单列表页
                showDialog2();
            }
        });
        return v;
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        orderList.clear();
        adapter.notifyDataSetChanged();
        vRefresh.setEnableLoadMore(true);
        mPage = 1;
        onLoadMore(refreshLayout);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        String time = "";
        if (mTimeFilter != null) {
            time = new SimpleDateFormat("yyyy-MM-dd").format(mTimeFilter);
        }
        APIRetrofit.getDefault().reqMyOrderList(Global.HEADER, type, mPage, mPageSize, time, et_name.getText().toString().trim())
                .compose(RxUtil.<BaseResult2<List<Order>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Order>>>() {
                    @Override
                    public void accept(BaseResult2<List<Order>> listBaseResult2) throws Exception {
                        hideProgress();
                        vRefresh.finishRefresh();
                        vRefresh.finishLoadMore();
                        if (listBaseResult2.isSuccess()) {
                            mPage++;
                            orderList.addAll(listBaseResult2.getData());
                            adapter.notifyDataSetChanged();
                        }

                        if (mPage == 1 && isDataEmpty(orderList)) {
                            empty_view.setVisibility(View.VISIBLE);
                        } else if (isDataEmpty(orderList)) {
                            vRefresh.setEnableLoadMore(false);
                        } else {
                            empty_view.setVisibility(View.GONE);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        empty_view.setVisibility(View.VISIBLE);
                    }
                });
    }
    private Disposable reqUserInfo() {
        return APIRetrofit.getDefault().getUserInfo(Global.HEADER, "1")
                .compose(RxUtil.<BaseResult2<List<Doctor>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Doctor>>>() {
                    @Override
                    public void accept(BaseResult2<List<Doctor>> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            List<Doctor> doctorList = result2.getData();
                            if (!isDataEmpty(doctorList)) {
                                Doctor doctor = doctorList.get(0);
                                Global.ORG_BALANCE = doctor.getMoney();
                                showDialog();
                            }
                        } else {

                        }
                        Logg.i("reqUserInfo.result2.getMsg()" + result2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }
    private class MyOrderListAdapter extends BaseQuickAdapter<Order, BaseViewHolder> {

        public MyOrderListAdapter(List<Order> orders) {
            super(R.layout.item_order_list_mine_fragment, orders);
        }

        @Override
        protected void convert(BaseViewHolder holder, final Order o) {
            RelativeLayout rl_item = holder.itemView.findViewById(R.id.rl_item);
            TextView tv_code = holder.itemView.findViewById(R.id.tv_code);
            TextView tv_status = holder.itemView.findViewById(R.id.tv_status);
            TextView tv_name = holder.itemView.findViewById(R.id.tv_name);
            TextView tv_item_num = holder.itemView.findViewById(R.id.tv_item_num);
            TextView tv_money = holder.itemView.findViewById(R.id.tv_money);
            TextView tv_date = holder.itemView.findViewById(R.id.tv_date);
            TextView tv_modify = holder.itemView.findViewById(R.id.tv_modify);// 修改订单
            TextView tv_pay = holder.itemView.findViewById(R.id.tv_pay);// 去付款
            TextView tv_cancel_refund = holder.itemView.findViewById(R.id.tv_cancel_refund);// 取消退款
            TextView tv_detail = holder.itemView.findViewById(R.id.tv_detail);// 查看详情

            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) rl_item.getLayoutParams();

            if (holder.getLayoutPosition() == 0) {
                params.topMargin = SizeUtils.dp2px(12);
                params.bottomMargin = SizeUtils.dp2px(6);
            } else if (holder.getLayoutPosition() == orderList.size() - 1) {
                params.topMargin = SizeUtils.dp2px(6);
                params.bottomMargin = SizeUtils.dp2px(12);
            } else {
                params.topMargin = SizeUtils.dp2px(6);
                params.bottomMargin = SizeUtils.dp2px(6);
            }

            tv_code.setText("订单编号:" + o.getOrder_num());
            final String status = PeUtil.getOrderStatus(o.getType());
            tv_status.setText(status);
            tv_name.setText(o.getName());
            tv_item_num.setText("共" + o.getCount() + "个检测项目");
            tv_money.setText("合计:¥" + o.getPrice());
            tv_date.setText("预约日期:" + o.getTime());

            // 订单状态 1 待付款,2 申请退款,3 订单取消,4 已退款,5 未接单,6 运输中,7 检验中,8 已出报告
            if (TextUtils.equals("1", o.getType())) {// 待付款
                tv_modify.setVisibility(View.GONE);
                tv_pay.setVisibility(View.VISIBLE);
                tv_cancel_refund.setVisibility(View.GONE);
                tv_detail.setVisibility(View.VISIBLE);
            } else if (TextUtils.equals("2", o.getType())) {// 申请退款
                tv_modify.setVisibility(View.GONE);
                tv_pay.setVisibility(View.GONE);
                tv_cancel_refund.setVisibility(View.GONE);
                tv_detail.setVisibility(View.VISIBLE);
            } else if (TextUtils.equals("3", o.getType())) {// 订单取消
                tv_modify.setVisibility(View.GONE);
                tv_pay.setVisibility(View.GONE);
                tv_cancel_refund.setVisibility(View.GONE);
                tv_detail.setVisibility(View.VISIBLE);
            } else if (TextUtils.equals("4", o.getType())) {// 已退款
                tv_modify.setVisibility(View.GONE);
                tv_pay.setVisibility(View.GONE);
                tv_cancel_refund.setVisibility(View.GONE);
                tv_detail.setVisibility(View.VISIBLE);
            } else if (TextUtils.equals("5", o.getType())) {// 未接单
                tv_modify.setVisibility(View.GONE);
                tv_pay.setVisibility(View.GONE);
                tv_cancel_refund.setVisibility(View.GONE);
                tv_detail.setVisibility(View.VISIBLE);
            } else if (TextUtils.equals("6", o.getType())) {// 运输中
                tv_modify.setVisibility(View.GONE);
                tv_pay.setVisibility(View.GONE);
                tv_cancel_refund.setVisibility(View.GONE);
                tv_detail.setVisibility(View.VISIBLE);
            } else if (TextUtils.equals("7", o.getType())) {// 检验中
                tv_modify.setVisibility(View.GONE);
                tv_pay.setVisibility(View.GONE);
                tv_cancel_refund.setVisibility(View.GONE);
                tv_detail.setVisibility(View.VISIBLE);
            } else if (TextUtils.equals("8", o.getType())) {// 已出报告
                tv_modify.setVisibility(View.GONE);
                tv_pay.setVisibility(View.GONE);
                tv_cancel_refund.setVisibility(View.GONE);
                tv_detail.setVisibility(View.VISIBLE);
            } else {
                tv_modify.setVisibility(View.GONE);
                tv_pay.setVisibility(View.GONE);
                tv_cancel_refund.setVisibility(View.GONE);
                tv_detail.setVisibility(View.VISIBLE);
            }

            tv_detail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putString("title", status);
                    bundle.putString("orderId", o.getId());
                    bundle.putString("orderStatus", o.getType());
                    bundle.putString("orderType", type);
                    startActivity(OrderDetailActivity.class, bundle);
                }
            });
            tv_pay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    orderNum = o.getOrder_num();
                    showProgressWithText(true, "");
                    reqUserInfo();
                }
            });
        }
    }

    private AlertDialog alert;// 弹窗
    private View alert_view;
    String payType = "2";// 支付方式 1 微信,2 支付宝,3 银联支付,4 余额支付

    public void showDialog() {// 弹窗界面
        alert.show();
        alert_view = View.inflate(getActivity(), R.layout.layout_alert_choose_pay_type, null);

        final RadioButton cb_ali = alert_view.findViewById(R.id.cb_ali);
        final RadioButton cb_wx = alert_view.findViewById(R.id.cb_wx);
        final RadioButton cb_union = alert_view.findViewById(R.id.cb_union);
        final RadioButton cb_balance = alert_view.findViewById(R.id.cb_balance);
        final TextView tv_balance0 = alert_view.findViewById(R.id.tv_balance0);// 显示余额数量

        RelativeLayout rl_ali = alert_view.findViewById(R.id.rl_ali);
        RelativeLayout rl_wechat = alert_view.findViewById(R.id.rl_wechat);
        RelativeLayout rl_union_pay = alert_view.findViewById(R.id.rl_union_pay);
        RelativeLayout rl_balance = alert_view.findViewById(R.id.rl_balance);

        tv_balance0.setText("余额支付 (¥" + Global.ORG_BALANCE + ")");

        rl_ali.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(true);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        cb_ali.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(true);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        rl_wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(true);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        cb_wx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(true);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        rl_union_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(true);
                cb_balance.setChecked(false);
            }
        });
        cb_union.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(true);
                cb_balance.setChecked(false);
            }
        });
        rl_balance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(true);
            }
        });
        cb_balance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(true);
            }
        });

        alert_view.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cb_ali.isChecked()) {
                    payType = "2";
                } else if (cb_wx.isChecked()) {
                    payType = "1";
                } else if (cb_union.isChecked()) {
                    payType = "3";
                } else if (cb_balance.isChecked()) {
                    payType = "4";
                }
                if (cb_ali.isChecked()) {// 支付宝
                    hideProgress();
                    reqAliPayInfo();
                    showProgress();
                } else if (cb_wx.isChecked()) {// 微信
                    hideProgress();
                    reqWxPayInfo();
                    showProgress();
                } else if (cb_union.isChecked()) {// 银联
                    hideProgress();
                    reqUPayPayInfo();
                    showProgress();
                } else if (cb_balance.isChecked()) {
                    hideProgress();
                    reqBalancePayInfo();
                    showProgress();
                }
                alert.dismiss();
            }
        });

        AlertUtil.setAlertBottomInStyle(alert.getWindow(), alert_view, getActivity());
    }

    private Disposable reqBalancePayInfo() {
        if (TextUtils.isEmpty(orderNum)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqPlaceOrderPayBalance(Global.HEADER, orderNum, payType)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            startActivity(PaySuccessActivity.class);
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_balance = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private Disposable reqUPayPayInfo() {
        if (TextUtils.isEmpty(orderNum)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqPlaceOrderPayUpay(Global.HEADER, orderNum, payType)
                .compose(RxUtil.<BaseResult2<UPayInfo>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<UPayInfo>>() {
                    @Override
                    public void accept(BaseResult2<UPayInfo> baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            uPay(baseResult2.getData().getTn());
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_upay = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private Disposable reqWxPayInfo() {
        if (TextUtils.isEmpty(orderNum)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqPlaceOrderPayWx(Global.HEADER, orderNum, payType)
                .compose(RxUtil.<BaseResult2<WxPayInfo>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<WxPayInfo>>() {
                    @Override
                    public void accept(BaseResult2<WxPayInfo> baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            wxPay(baseResult2);
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_wx = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取微信支付信息错误");
                    }
                });
    }

    private Disposable reqAliPayInfo() {
        if (TextUtils.isEmpty(orderNum)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqPlaceOrderPayAli(Global.HEADER, orderNum, payType)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            String orderInfo = (String) baseResult2.getData();
                            aliPay(orderInfo);
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_ali = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 调起银联支付
    private void uPay(String tn) {
        UPPayAssistEx.startPay(getContext(), null, null, tn, MyApp.unionPayMode);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        String str = data.getExtras().getString("pay_result");
        if (str.equalsIgnoreCase("success")) {
            paySuc();
        } else if (str.equalsIgnoreCase("fail")) {
            ToastUtils.showShort("银联支付失败");
        } else if (str.equalsIgnoreCase("cancel")) {
            ToastUtils.showShort("您取消了银联支付");
        }
    }

    // 调起微信支付
    private void wxPay(BaseResult2<WxPayInfo> baseResult2) {
        WxPayInfo wxPayInfo = baseResult2.getData();
        PayReq request = new PayReq();
        request.appId = wxPayInfo.getAppid();
        request.partnerId = wxPayInfo.getPartnerid();
        request.prepayId = wxPayInfo.getPrepayid();
        request.packageValue = "Sign=WXPay";
        request.nonceStr = wxPayInfo.getNoncestr();
        request.timeStamp = wxPayInfo.getTimestamp();
        request.sign = wxPayInfo.getSign();
        msgApi.sendReq(request);
    }

    // 调起支付宝支付
    private void aliPay(final String orderInfo) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(getActivity());
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = 20100851;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        }).start();
    }

    @SuppressWarnings("all")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            //返回码，标识支付状态，含义如下：9000——订单支付成功 8000——正在处理中 4000——订单支付失败 5000——重复请求 6001——用户中途取消 6002——网络连接出错
            if (msg.what == 20100851) {
                PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                String payStatus = payResult.getResultStatus();
                if (TextUtils.equals(payStatus, "9000")) {// 判断resultStatus 为9000则代表支付成功
                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                    paySuc();
                } else if (TextUtils.equals(payStatus, "6001")) {
                    ToastUtils.showShort("取消支付");
                } else {
                    // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    ToastUtils.showShort("支付失败");
                }
            }
        }
    };

    private void paySuc() {
        startActivity(PaySuccessActivity.class);
        EventBus.getDefault().post(new RefreshEvent("paySucc"));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshEvent(RefreshEvent e) {
        if ("cancelOrder".equals(e.getAction())) {
            if ("3".equals(type)) {
                this.vRefresh.autoRefresh();
            } else if ("0".equals(type)) {
                Order order = null;
                for (Order o : orderList) {
                    if (e.getExtra().equals(o.getId())) {
                        order = o;
                    }
                }
                if (order != null) {
                    adapter.remove(orderList.indexOf(order));
                }
            }else if("1".equals(type)){
                this.vRefresh.autoRefresh();
            }
        } else if ("paySucc".equals(e.getAction())) {
            if ("0".equals(type) || "1".equals(type) || "2".equals(type)) {
                vRefresh.autoRefresh();
            }
        } else if ("refundOrder".equals(e.getAction())) {
            if ("2".equals(type) || "4".equals(type)) {
                vRefresh.autoRefresh();
            }
        } else if ("refreshMyOrder".equals(e.getAction()) && type.equals(e.getExtra())) {
            vRefresh.autoRefresh();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View v) {
        if (v == tv_ok) {// 搜索
            showProgress();
            onRefresh(vRefresh);
        }
        if (v == ll_time) {// 选择时间
            initTimePicker();
            pvTime.show();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        onRefresh(vRefresh);
    }

    private TimePickerView pvTime;

    private void initTimePicker() {//Dialog 模式下，在底部弹出
        pvTime = new TimePickerBuilder(getActivity(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
//                Toast.makeText(getActivity(), getTime(date), Toast.LENGTH_SHORT).show();
                Log.i("pvTime", "onTimeSelect");
                tv_day.setText(getTime(date));
                mTimeFilter = date;
            }
        }).setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
            @Override
            public void onTimeSelectChanged(Date date) {
                Log.i("pvTime", "onTimeSelectChanged");
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .isDialog(true) // 默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.i("pvTime", "onCancelClickListener");
                    }
                })
                .setItemVisibleCount(7) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier(2.0f)
                .isAlphaGradient(true)
                .setTitleText("选择时间")
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
        return format.format(date);
    }

    private AlertDialog alert2;// 弹窗
    private View alert_view2;

    public void showDialog2() {// 弹窗
        alert2.show();
        alert_view2 = View.inflate(getContext(), R.layout.layout_alert_com_alert, null);

        TextView tv_1 = alert_view2.findViewById(R.id.tv_1);
        TextView tv_2 = alert_view2.findViewById(R.id.tv_2);
        TextView tv_title = alert_view2.findViewById(R.id.tv_title);
        tv_1.setText("继续支付");
        tv_2.setText("确认离开");
        tv_title.setText("您的订单未支付，请尽快完成支付。");
        tv_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert2.dismiss();
                showDialog();
            }
        });
        tv_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert2.dismiss();
            }
        });

        AlertUtil.setAlertCenterStyle(alert2.getWindow(), alert_view2, getActivity());
    }

}